import os
import sys
import wave
import pyaudio

import config
import model_store

logger = config.get_logger()


# 实用方法， 中立方法， 不会设计同目录的其他python文件
def add_project_to_pythonpath(project_path=None):
    """将当前项目加入pythonpath，默认当前项目为本文件所在路径的上级目录，可自己指定"""
    #  __file__ 是内置变量，表示当前文件的绝对路径， os.path.dirname是获得一个文件的所在目录
    this_dir = os.path.dirname(__file__)
    project_path = project_path if project_path is not None else this_dir + '../'
    if project_path not in sys.path:
        sys.path.insert(0, project_path)
    logger.info('add project path to pythonpath: %s' % project_path)


def inference_one_sequence(wav_file_path: str):
    """
    输入： wav file的path
    输出； 识别的一句话，text
    """
    model = model_store.GateConv().load(config.MODEL_DIR + 'model_param_epoch10_2023_02_14-16_21_22.pt')
    text = model.predict(wav_file_path)
    return text


def record_your_voice_to_wav(record_time: int = 5,
                             record_wav_save_path: str =
                             config.RECORD_SAVE_DIR + 'record_'+config.utils_file.get_now()+'.wav'):
    """开启录音设备，录制一段时间的声音，并将声音存储至指定目录
    输入： 录音时长(单位秒)，录音保存路径
    输出： 无"""
    num_samples = 2000
    time = 10
    channel = 1
    sample_rate = 16000
    sample_width = 2
    print('开始录音。。。持续时长：' + str(record_time) + 's')
    stream = pyaudio.PyAudio().open(
        format=pyaudio.paInt16,
        channels=channel,
        rate=sample_rate, input=True,
        frames_per_buffer=num_samples)
    my_buffer = []
    count = 0
    while count < time * record_time:
        data = stream.read(1024)
        my_buffer.append(data)
        count += 1
        print(".", end="", flush=True)
    wf = wave.open(record_wav_save_path, "wb")
    wf.setnchannels(channel)
    wf.setsampwidth(sample_width)
    wf.setframerate(sample_rate)
    wf.writeframes(b"".join(my_buffer))
    wf.close()
    stream.close()





if __name__ == '__main__':
    record_your_voice_to_wav(2)
